package work_aliface.compare;

public class index {

    public static void main(String[] args) {
        long t1 = System.currentTimeMillis();
        ThreadDemo1 td = new ThreadDemo1();
        new Thread(td).start();
        while (true) {
            //  方式一，加个同步锁
//            synchronized (td) {
                if (td.isFlag()) {
                    System.out.println("########");
                    System.out.println(System.currentTimeMillis() - t1);
                    break;
                }
//            }
        }


    }
}

class ThreadDemo1 implements Runnable {
    // 方式二，加个volatile
    private volatile boolean flag = false;
//    private boolean flag = false;

    public void run() {
        try {
            // 该线程 sleep(200), 导致了程序无法执行成功
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        flag = true;

        System.out.println("flag=" + isFlag());
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}